﻿// IWebWF
// Copyright (c) 2008
// by Michael Washington
// Webmaster@ADefWebserver.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
//
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using IWebWFCore;
using System.Text;
using System.Net.Mail;
using System.Net;
using SampleWebService;
using System.Workflow.Activities;
using System.Workflow.Runtime;
using System.Collections;

namespace IWebWF
{
    public partial class Administration_Default : System.Web.UI.Page
    {
        string UserName;
        string Password;

        protected void Page_Load(object sender, EventArgs e)
        {
            // Must be a logged in Administrator             
            if (User.Identity.IsAuthenticated)
            {
                FormsIdentity id = (FormsIdentity)User.Identity;
                FormsAuthenticationTicket ticket = id.Ticket;
                if (!(ticket.UserData.ToString() == "Administrators"))
                {
                    Response.Redirect("../Default.aspx");
                    Response.End();
                }

                UserName = ticket.Name;
                Password = GetPassword();
            }
            else
            {
                Response.Redirect("../Default.aspx");
                Response.End();
            }

            if (!Page.IsPostBack)
            {
                txtWebserviceURL.Text = GetWebServiceBase();
                mvAdministration.SetActiveView(vwGeneralSettings);
                LoadGeneralSettings();
            }
        }

        #region GetPassword
        private string GetPassword()
        {
            IWebWFDataContext IWebWFDataContext = new IWebWFDataContext();
            var result = from WFUser in IWebWFDataContext.IWebWFUsers
                         where WFUser.UserName == UserName
                         where WFUser.SuperUser == true
                         select WFUser;

            IWebWFUser IWebWFUser = (IWebWFUser)result.FirstOrDefault();
            return IWebWFUser.Password;
        }
        #endregion

        #region LoadGeneralSettings
        private void LoadGeneralSettings()
        {
            GeneralSettings GeneralSettings = new GeneralSettings();
            lblVersion.Text = GeneralSettings.Version;
            txtMaxPasswordAttempts.Text = Convert.ToString(GeneralSettings.MaxLoginAttempts);
            txtSMTPEmailServer.Text = GeneralSettings.SMTPServer;
            rbAuthendication.SelectedValue = GeneralSettings.SMTPAuthendication;
            chkSecureAccess.Checked = GeneralSettings.SMTPSecure;
            txtSMTPUsername.Text = GeneralSettings.SMTPUserName;
            txtSMTPPassword.Text = GeneralSettings.SMTPPassword;
            txtSMTPFrom.Text = GeneralSettings.SMTPFromEmail;
        }
        #endregion

        #region Navigation
        protected void AdministrationMenu_MenuItemClick(object sender, MenuEventArgs e)
        {
            switch (e.Item.Value)
            {
                case "General Settings":
                    mvAdministration.SetActiveView(vwGeneralSettings);
                    break;
                case "Status":
                    mvAdministration.SetActiveView(vwStatus);
                    break;
                case "User Management":
                    mvAdministration.SetActiveView(vwUserManagement);
                    break;
                case "Application Log":
                    mvAdministration.SetActiveView(vwApplicationLog);
                    break;
                case "Sample Client":
                    mvAdministration.SetActiveView(vwClient);
                    break;
            }
        }

        protected void lnkBackFromDetails_Click(object sender, EventArgs e)
        {
            mvAdministration.SetActiveView(vwStatus);
        }
        #endregion

        #region Update Settings
        protected void btnUpdateSettings_Click(object sender, EventArgs e)
        {
            try
            {
                GeneralSettings.UpdateMaxLoginAttempts(Convert.ToInt32(txtMaxPasswordAttempts.Text.Trim()));
                GeneralSettings.UpdateSMTPServer(txtSMTPEmailServer.Text.Trim());
                GeneralSettings.UpdateSMTPAuthendication(rbAuthendication.SelectedValue);
                GeneralSettings.UpdateSMTPSecure(chkSecureAccess.Checked);
                GeneralSettings.UpdateSMTPUserName(txtSMTPUsername.Text.Trim());
                GeneralSettings.UpdateSMTPPassword(txtSMTPPassword.Text.Trim());
                GeneralSettings.UpdateSMTPFromEmail(txtSMTPFrom.Text.Trim());
            }
            catch (Exception ex)
            {
                lblUpdated.Text = ex.Message;
                return;
            }

            lblUpdated.Text = "Updated!";
        }
        #endregion

        #region Send Test Email
        protected void lnkTestEmail_Click(object sender, EventArgs e)
        {
            // Send Test Email
            // For normal emails use this constructor:
            // SendMail(string MailTo, string Cc, string Bcc, string ReplyTo, string Subject, string Body, string strAttachment)

            string[] arrAttachments = new string[0];
            string strEmailResponse = Email.SendMail(txtSMTPFrom.Text.Trim(), txtSMTPFrom.Text.Trim(), "", "", txtSMTPFrom.Text.Trim(), MailPriority.Normal, "IWebWF Email", Encoding.UTF8, "A test email sent from IWebWF",
            arrAttachments, txtSMTPEmailServer.Text.Trim(), rbAuthendication.SelectedValue, txtSMTPUsername.Text.Trim(), txtSMTPPassword.Text.Trim(), chkSecureAccess.Checked);

            lblUpdated.Text = (strEmailResponse.Trim() == "") ? "Email Sent." : strEmailResponse;
        }
        #endregion

        #region lnkRefresh
        protected void lnkRefresh_Click(object sender, EventArgs e)
        {
            gvApplicationLog.DataBind();
        }
        #endregion

        #region lvUsers_ItemInserted
        protected void lvUsers_ItemInserted(object sender, ListViewInsertedEventArgs e)
        {
            if (e.Exception != null)
            {
                lblError.Text = e.Exception.Message;
                e.KeepInInsertMode = true;
                e.ExceptionHandled = true;
            }
        }
        #endregion

        #region lvUsers_ItemUpdated
        protected void lvUsers_ItemUpdated(object sender, ListViewUpdatedEventArgs e)
        {
            if (e.Exception != null)
            {
                lblError.Text = e.Exception.Message;
                e.KeepInEditMode = true;
                e.ExceptionHandled = true;
            }
        }
        #endregion

        // Sample Client

        #region GetWebServiceBase
        private string GetWebServiceBase()
        {
            string strWebServiceBase = String.Format(@"{0}://", this.Request.Url.Scheme);
            strWebServiceBase = String.Format(@"{0}{1}", strWebServiceBase, this.Request.Url.Host.Replace(@"\", @"/"));
            strWebServiceBase = String.Format(@"{0}{1}", strWebServiceBase, ((this.Request.Url.Port == 80) ? "" : ":" + this.Request.Url.Port.ToString()));
            strWebServiceBase = String.Format(@"{0}{1}", strWebServiceBase, this.Request.ApplicationPath.Replace(@"\", ""));
            strWebServiceBase = String.Format(@"{0}/webservice/SampleWorkflow.asmx", strWebServiceBase);
            return strWebServiceBase;
        }
        #endregion

        #region CreateSampleRequest
        protected void btnCreateSampleRequest_Click(object sender, EventArgs e)
        {
            // Reference to the web service
            Workflow_WebService SampleClient = new Workflow_WebService();
            // Enable cookies
            SampleClient.CookieContainer = new System.Net.CookieContainer();
            // Set the address to the web service
            SampleClient.Url = txtWebserviceURL.Text.Trim();
            // Call the method to start the workflow
            Guid WorkflowInstanceID = SampleClient.StartWorkflow(UserName, Password);
            // Get the WorkflowInstanceID
            txtCurrentWorkflowID.Text = WorkflowInstanceID.ToString();

            lblWorkflowStarted.Visible = true;
        }
        #endregion

        #region SetStatus
        protected void btnSetStatus_Click(object sender, EventArgs e)
        {
            // Reference to the web service
            Workflow_WebService SampleClient = new Workflow_WebService();
            // Set the address to the web service
            SampleClient.Url = txtWebserviceURL.Text.Trim();
            // Create a URI
            Uri SampleClientUri = new Uri(SampleClient.Url);
            // Enable cookies
            SampleClient.CookieContainer = new System.Net.CookieContainer();
            // Use the URI to obtain a collection of the cookies
            CookieCollection mycollection = SampleClient.CookieContainer.GetCookies(SampleClientUri);
            // Add the current WorkflowInstanceId to the cookie collection 
            // that will be passed to the web service
            SampleClient.CookieContainer.SetCookies
                (
                SampleClientUri,
                String.Format("{0}={1}", "WF_WorkflowInstanceId", txtCurrentWorkflowID.Text.Trim())
                );
            // Call the ChangeStatus web method and pass the new Status
            SampleClient.ChangeStatus(UserName, Password, txtWorkflowStatus.Text);
        }
        #endregion

        #region GetStatus
        protected void btnGetStatus_Click(object sender, EventArgs e)
        {
            // Reference to the web service
            Workflow_WebService SampleClient = new Workflow_WebService();
            // Set the address to the web service
            SampleClient.Url = txtWebserviceURL.Text.Trim();
            // Create a URI
            Uri SampleClientUri = new Uri(SampleClient.Url);
            // Enable cookies
            SampleClient.CookieContainer = new System.Net.CookieContainer();
            // Use the URI to obtain a collection of the cookies
            CookieCollection mycollection = SampleClient.CookieContainer.GetCookies(SampleClientUri);
            // Add the current WorkflowInstanceId to the cookie collection 
            // that will be passed to the web service
            SampleClient.CookieContainer.SetCookies
                (
                SampleClientUri,
                String.Format("{0}={1}", "WF_WorkflowInstanceId", txtCurrentWorkflowID.Text.Trim())
                );
            // Call the VacationRequestStatus web method and retrieve the status
            lblRequestStatus.Text = SampleClient.GetStatus(UserName, Password); 
        }
        #endregion

        #region StopWorkflow
        protected void btnStopWorkflow_Click(object sender, EventArgs e)
        {
            // Reference to the web service
            Workflow_WebService SampleClient = new Workflow_WebService();
            // Set the address to the web service
            SampleClient.Url = txtWebserviceURL.Text.Trim();
            // Create a URI
            Uri SampleClientUri = new Uri(SampleClient.Url);
            // Enable cookies
            SampleClient.CookieContainer = new System.Net.CookieContainer();
            // Use the URI to obtain a collection of the cookies
            CookieCollection mycollection = SampleClient.CookieContainer.GetCookies(SampleClientUri);
            // Add the current WorkflowInstanceId to the cookie collection 
            // that will be passed to the web service
            SampleClient.CookieContainer.SetCookies
                (
                SampleClientUri,
                String.Format("{0}={1}", "WF_WorkflowInstanceId", txtCurrentWorkflowID.Text.Trim())
                );
            // Stop the workflow and delete the workflow instance
            SampleClient.StopWorkflow(UserName, Password);
            lblWorkflowStopped.Visible = true;
        }
        #endregion

        #region lnkRefreshStatus_Click
        protected void lnkRefreshStatus_Click(object sender, EventArgs e)
        {
            gvStatus.DataBind();
        }
        #endregion

        // Workflow Details
        protected void gvStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            mvAdministration.SetActiveView(vwWorkflowDetails);
            GridView GridView = (GridView)sender;
            Guid Guid = new Guid(GridView.SelectedValue.ToString());

            WorkflowRuntime WorkflowRuntime = new WorkflowRuntime("WorkflowRuntime");
            WorkflowRuntime.StartRuntime();
            WorkflowInstance WorkflowInstance = WorkflowRuntime.GetWorkflow(Guid);
            System.Workflow.ComponentModel.Activity Activity = WorkflowInstance.GetWorkflowDefinition();
            
            StringBuilder WorkflowDetails = new StringBuilder();
            WorkflowDetails.Append(String.Format("<b>QualifiedName:</b> {0}", Activity.QualifiedName) + "<br>");
            WorkflowDetails.Append(String.Format("<b>Description:</b> {0}", Activity.Description) + "<br>");
            WorkflowDetails.Append(String.Format("<b>Enabled:</b> {0}", Activity.Enabled.ToString()) + "<br>");
            WorkflowDetails.Append(String.Format("<b>ExecutionStatus:</b> {0}", Activity.ExecutionStatus.ToString()) + "<br>");

            var UserData = Activity.UserData.Values;
            foreach (var Data in UserData)
            {
                if (Data.ToString().ToLower() == "system.collections.hashtable")
                {
                    Hashtable Hashtable = (Hashtable)Data;
                    foreach (var HashData in Hashtable.Keys)
                    {
                        WorkflowDetails.Append(String.Format("<b>HashTable Data:</b> {0}", HashData.ToString()) + "<br>");
                    }
                }
            }           

            lblWorkflowDetails.Text = WorkflowDetails.ToString();
            WorkflowRuntime.StopRuntime();
            WorkflowRuntime.Dispose();
        }
}
}
